package com.chuangjiangx.member.manager.web.web.score.controller;

import com.chuangjiangx.commons.CJBeanUtils;
import com.chuangjiangx.commons.PageUtils;
import com.chuangjiangx.commons.page.PagingResult;
import com.chuangjiangx.commons.request.Page;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.member.manager.basic.web.controller.BaseController;
import com.chuangjiangx.member.manager.basic.web.interceptor.Login;
import com.chuangjiangx.member.manager.basic.web.interceptor.Permissions;
import com.chuangjiangx.member.manager.common.Constants;
import com.chuangjiangx.member.manager.common.RequestHeadersUtil;
import com.chuangjiangx.member.manager.common.ThreadLocalUser;
import com.chuangjiangx.member.manager.web.web.score.request.*;
import com.chuangjiangx.member.manager.web.web.score.response.*;
import com.chuangjiangx.member.score.ddd.dal.condition.*;
import com.chuangjiangx.member.score.ddd.query.MbrScoreGiftRuleCountQuery;
import com.chuangjiangx.member.score.ddd.query.dto.MemberScoreGiftListDTO;
import com.chuangjiangx.member.score.ddd.query.dto.ScoreGiftRuleCountByGiftDTO;
import com.chuangjiangx.member.score.ddd.query.dto.ScoreGiftRuleCountByStoreDTO;
import com.chuangjiangx.member.score.ddd.query.dto.ScoreGiftRuleCountByTimeDTO;
import com.sun.jmx.snmp.ThreadContext;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 积分兑换统计
 */
@RestController
@RequestMapping(value = "/api/mbr/score-gift-count", produces = "application/json")
public class MbrScoreGiftRuleCountController extends BaseController {
    @Autowired
    private MbrScoreGiftRuleCountQuery mbrScoreGiftRuleCountQuery;




    /**
     * 按照时间前10个查询积分兑换--商户权限
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftRuleCountByTimeDTO
     */
    @RequestMapping(value = "/count-by-time-chart-all")
    @Login
    @Permissions("50040")
    public Response scoreGiftCountTop10ByTimeForMerchant(
                                                         @Validated @RequestBody ScoreGiftCountByTimeRequest param) {
        ScoreGiftRuleByTimeCondition condition = new ScoreGiftRuleByTimeCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        PageUtils.copyPage(condition, param.getPage());

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setStoreId(user.getStoreId());
        condition.setMerchantId(user.getMerchantId());

        List<ScoreGiftRuleCountByTimeDTO> list = mbrScoreGiftRuleCountQuery.countTop10ByTimeForMerchant(condition);
        return ResponseUtils.success("dataList", list);
    }


    /**
     * 按照时间前10个查询积分兑换--门店权限
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftRuleCountByTimeDTO
     */
    @RequestMapping(value = "/count-by-time-chart-its")
    @Login
    @Permissions("51020")
    public Response scoreGiftCountTop10ByTimeForStore(
                                                      @Validated @RequestBody ScoreGiftCountByTimeRequest param) {
        ScoreGiftRuleByTimeCondition condition = new ScoreGiftRuleByTimeCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        PageUtils.copyPage(condition, param.getPage());

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setStoreId(user.getStoreId());
        condition.setMerchantId(user.getMerchantId());

        List<ScoreGiftRuleCountByTimeDTO> list = mbrScoreGiftRuleCountQuery.countTop10ByTimeForStore(condition);
        return ResponseUtils.success("dataList", list);

    }

    /**
     * 按照时间查询积分兑换明细--商户权限
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftCountByTimeDetailResponse
     */
    @RequestMapping(value = "/count-by-time-detail-all")
    @Login
    @Permissions("50041")
    public Response scoreGiftCountByTimeDetailForMerchant(
                                                          @Validated @RequestBody ScoreGiftCountByTimeDetailRequest param) throws InvocationTargetException, IllegalAccessException {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setStoreId(user.getStoreId());
        condition.setMerchantId(user.getMerchantId());
        BeanUtils.copyProperties(condition, param);
        PageUtils.copyPage(condition, param.getPage());
        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByTimeForMerchant(condition);
        List<ScoreGiftCountByTimeDetailResponse> resList = CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByTimeDetailResponse.class);
        return ResponseUtils.successPage(param.getPage(), list, "dataList", resList);
    }


    /**
     * 按照时间查询积分兑换明细--商户权限 导出
     */
    @RequestMapping(value = "/export/count-by-time-detail-all")
    @Login
    public void exportScoreGiftCountByTimeDetailForMerchant(
                                                            HttpServletResponse response,
                                                            HttpServletRequest request) throws InvocationTargetException, IllegalAccessException, IOException, ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String pageNo = request.getParameter("pageNO");
        String everyPageCount = request.getParameter("everyPageCount");
        ScoreGiftCountByTimeDetailRequest param = new ScoreGiftCountByTimeDetailRequest();
        if ("" != startTime) {
            param.setStartTime(sdf.parse(startTime));
        }
        if ("" != endTime) {
            param.setEndTime(sdf.parse(endTime));
        }

        Page page = new Page();
        if ("" != pageNo) {
            page.setPageNO(Integer.parseInt(pageNo));
        }
        if ("" != everyPageCount) {
            page.setEveryPageCount(EXPORT_SIZE);
        }
        param.setPage(page);

        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "按照时间查询积分兑换明细");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            List<ScoreGiftCountByTimeDetailResponse> list = getExportScoreGiftCountByTimeDetailForMerchant(param);
            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            getExportScoreGiftCountByTimeDetail(sdf, bw, list);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            if (osw != null) {
                osw.close();
                osw = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }
    }

    private List<ScoreGiftCountByTimeDetailResponse> getExportScoreGiftCountByTimeDetailForMerchant(@Validated @RequestBody ScoreGiftCountByTimeDetailRequest param) throws IllegalAccessException, InvocationTargetException {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setStoreId(user.getStoreId());
        condition.setMerchantId(user.getMerchantId());

        BeanUtils.copyProperties(condition, param);
        PageUtils.copyPage(condition, param.getPage());
        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByTimeForMerchant(condition);
        return CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByTimeDetailResponse.class);
    }

    /**
     * 按照时间查询积分兑换明细--门店权限
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftCountByTimeDetailResponse
     */
    @RequestMapping(value = "/count-by-time-detail-its")
    @Login
    @Permissions("51021")
    public Response scoreGiftCountByTimeDetailForStore(HttpSession session, @Validated @RequestBody ScoreGiftCountByTimeDetailRequest param) throws InvocationTargetException, IllegalAccessException {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setStoreId(user.getStoreId());
        condition.setMerchantId(user.getMerchantId());

        BeanUtils.copyProperties(condition, param);
        PageUtils.copyPage(condition, param.getPage());
        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByTimeForStore(condition);
        List<ScoreGiftCountByTimeDetailResponse> resList = CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByTimeDetailResponse.class);
        return ResponseUtils.successPage(param.getPage(), list, "dataList", resList);
    }

    /**
     * 按照时间查询积分兑换明细--门店权限 导出
     */
    @RequestMapping(value = "/export/count-by-time-detail-its")
    @Login
    public void exportScoreGiftCountByTimeDetailForStore(HttpSession session,
                                                         HttpServletResponse response,
                                                         HttpServletRequest request) throws InvocationTargetException, IllegalAccessException, ParseException, IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String pageNo = request.getParameter("pageNO");
        ScoreGiftCountByTimeDetailRequest param = new ScoreGiftCountByTimeDetailRequest();
        if ("" != startTime) {
            param.setStartTime(sdf.parse(startTime));
        }
        if ("" != endTime) {
            param.setEndTime(sdf.parse(endTime));
        }

        Page page = new Page();
        if ("" != pageNo) {
            page.setPageNO(Integer.parseInt(pageNo));
        }
        page.setEveryPageCount(EXPORT_SIZE);
        param.setPage(page);

        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "按照时间查询积分兑换明细");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            List<ScoreGiftCountByTimeDetailResponse> list = getExportScoreGiftCountByTimeDetailForStore(session, param);
            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            getExportScoreGiftCountByTimeDetail(sdf, bw, list);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            if (osw != null) {
                osw.close();
                osw = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }

    }

    private void getExportScoreGiftCountByTimeDetail(SimpleDateFormat sdf, BufferedWriter bw, List<ScoreGiftCountByTimeDetailResponse> list) throws IOException {
        bw.append("序号").append(",")
                .append("兑换时间").append(",")
                .append("会员卡号").append(",")
                .append("会员名称").append(",")
                .append("手机号").append(",")
                .append("兑换积分").append(",")
                .append("兑换规则").append(",")
                .append("当前可用积分").append(",")
                .append("操作人").append(",")
                .append("来源").append(",").append("\r");

        if (list != null && !list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                ScoreGiftCountByTimeDetailResponse data = list.get(i);
                String createTime = null;
                if (data.getCreateTime() != null) {
                    createTime = sdf.format(data.getCreateTime());
                }
                bw.append(String.valueOf(i + 1)).append(",")
                        .append(createTime == null ? "" : createTime).append(",")
                        .append(data.getMemberCardNum() == null ? "" : data.getMemberCardNum()).append(",")
                        .append(data.getName() == null ? "" : data.getName()).append(",")
                        .append(data.getMobile() == null ? "" : data.getMobile()).append(",")
                        .append(data.getScore() == null ? "" : data.getScore().toString()).append(",")
                        .append(data.getRuleName() == null ? "" : data.getRuleName()).append(",")
                        .append(data.getAvailableScore() == null ? "" : data.getAvailableScore().toString()).append(",")
                        .append(data.getStoreUserName() == null ? "" : data.getStoreUserName()).append(",")
                        .append(data.getTerminalTypeName() == null ? "" : data.getTerminalTypeName()).append(",")
                        .append("\r");
            }
        }
    }

    private List<ScoreGiftCountByTimeDetailResponse> getExportScoreGiftCountByTimeDetailForStore(HttpSession session, @Validated @RequestBody ScoreGiftCountByTimeDetailRequest param) throws IllegalAccessException, InvocationTargetException {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setStoreId(user.getStoreId());
        condition.setMerchantId(user.getMerchantId());

        BeanUtils.copyProperties(condition, param);
        PageUtils.copyPage(condition, param.getPage());
        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByTimeForStore(condition);
        return CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByTimeDetailResponse.class);
    }


    /**
     * 按照门店查询前10个积分兑换--商户
     *
     * @return 列表
     * @map dataList
     * @see //MemberScoreGiftCountByStoreDTO
     */
    @RequestMapping(value = "/count-by-store-chart-all")
    @Login
    @Permissions("50042")
    public Response scoreGiftCountTop10ByStoreForMerchant(
                                                          @Validated @RequestBody ScoreGiftCountByStoreRequest param) {
        ScoreGiftRuleCountByStoreCondition condition = new ScoreGiftRuleCountByStoreCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setMerchantId(user.getMerchantId());

        List<ScoreGiftRuleCountByStoreDTO> list =
                mbrScoreGiftRuleCountQuery.countTop10ByStoreForMerchant(condition);
        return ResponseUtils.success("dataList", list);

    }


    /**
     * 按照门店查询列表--商户
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftCountByStoreResponse
     */
    @RequestMapping(value = "/count-by-store-list-all")
    @Login
    @Permissions("50043")
    public Response scoreGiftCountByStoreList(
                                              @Validated @RequestBody ScoreGiftCountByStoreRequest param) {
        MemberScoreGiftCountListByStoreCondition condition = new MemberScoreGiftCountListByStoreCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setMerchantId(user.getMerchantId());
        PageUtils.copyPage(condition, param.getPage());

        PagingResult<ScoreGiftRuleCountByStoreDTO> list =
                mbrScoreGiftRuleCountQuery.countByStoreForMerchant(condition);
        List<ScoreGiftCountByStoreResponse> respList = CJBeanUtils.convertCollection(
                list.getItems(), ScoreGiftCountByStoreResponse.class);
        return ResponseUtils.successPage(param.getPage(), list, "dataList", respList);
    }


    /**
     * 按照门店查询列表--商户
     */
    @RequestMapping(value = "/export/count-by-store-list-all")
    @Login
    public void exportScoreGiftCountByStoreList(
                                                HttpServletResponse response,
                                                HttpServletRequest request) throws IOException, ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String pageNo = request.getParameter("pageNO");
        String everyPageCount = request.getParameter("everyPageCount");
        ScoreGiftCountByStoreRequest param = new ScoreGiftCountByStoreRequest();
        if ("" != startTime) {
            param.setStartTime(sdf.parse(startTime));
        }
        if ("" != endTime) {
            param.setEndTime(sdf.parse(endTime));
        }

        Page page = new Page();
        if ("" != pageNo) {
            page.setPageNO(Integer.parseInt(pageNo));
        }
        if ("" != everyPageCount) {
            page.setEveryPageCount(Integer.parseInt(everyPageCount));
        }
        param.setPage(page);
        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "按照门店查询列表");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            List<ScoreGiftCountByStoreResponse> list = getExportScoreGiftCountByStoreList(param);
            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            bw.append("序号").append(",")
                    .append("兑换门店").append(",")
                    .append("兑换量").append(",").append("\r");
            if (list != null && !list.isEmpty()) {
                for (int i = 0; i < list.size(); i++) {
                    ScoreGiftCountByStoreResponse data = list.get(i);
                    bw.append(String.valueOf(i + 1)).append(",")
                            .append(data.getStoreName() == null ? "" : data.getStoreName()).append(",")
                            .append(data.getNum().toString()).append(",")
                            .append("\r");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            if (osw != null) {
                osw.close();
                osw = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }

    }

    private List<ScoreGiftCountByStoreResponse> getExportScoreGiftCountByStoreList(@Validated @RequestBody ScoreGiftCountByStoreRequest param) {
        MemberScoreGiftCountListByStoreCondition condition = new MemberScoreGiftCountListByStoreCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setMerchantId(user.getMerchantId());
        PageUtils.copyPage(condition, param.getPage());

        PagingResult<ScoreGiftRuleCountByStoreDTO> list =
                mbrScoreGiftRuleCountQuery.countByStoreForMerchant(condition);
        return CJBeanUtils.convertCollection(
                list.getItems(), ScoreGiftCountByStoreResponse.class);
    }


    /**
     * 按照门店查询列表详情--商户
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftCountByScoreDetailResponse
     */
    @RequestMapping(value = "/count-by-store-detail-all")
    @Login
    @Permissions("50044")
    public Response scoreGiftCountByStoreDetail(HttpSession session,
                                                @Validated @RequestBody ScoreGiftCountByScoreDetailRequest param) throws Exception {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        if (param.getStoreId() != null) {
            param.setMerchantUserId(null);
        }
        BeanUtils.copyProperties(condition, param);
        PageUtils.copyPage(condition, param.getPage());
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setMerchantId(user.getMerchantId());

        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByStoreGiftForMerchant(condition);
        List<ScoreGiftCountByScoreDetailResponse> resList = CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByScoreDetailResponse.class);
        return ResponseUtils.successPage(param.getPage(), list, "dataList", resList);
    }


    /**
     * 按照门店查询列表详情--商户 导出
     */
    @RequestMapping(value = "/export/count-by-store-detail-all")
    @Login
    public void exportScoreGiftCountByStoreDetail(HttpSession session,
                                                  HttpServletResponse response,
                                                  HttpServletRequest request) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String storeId = request.getParameter("storeId");
        String merchantUserId = request.getParameter("merchantUserId");
        String terminalType = request.getParameter("terminalType");
        String nameOrMobile = request.getParameter("nameOrMobile");
        String scoreGiftId = request.getParameter("scoreGiftId");
        String pageNo = request.getParameter("pageNO");
        ScoreGiftCountByScoreDetailRequest param = new ScoreGiftCountByScoreDetailRequest();
        if ("" != startTime) {
            param.setStartTime(sdf.parse(startTime));
        }
        if ("" != endTime) {
            param.setEndTime(sdf.parse(endTime));
        }
        if ("" != storeId) {
            param.setStoreId(Long.parseLong(storeId));
        }
        if ("" != merchantUserId) {
            param.setMerchantUserId(Long.parseLong(merchantUserId));
        }
        if ("" != terminalType) {
            param.setTerminalType(Byte.valueOf(terminalType));
        }
        if ("" != nameOrMobile) {
            param.setNameOrMobile(nameOrMobile);
        }
        if ("" != scoreGiftId) {
            param.setScoreGiftId(Long.parseLong(scoreGiftId));
        }


        Page page = new Page();
        if ("" != pageNo) {
            page.setPageNO(Integer.parseInt(pageNo));
        }
        page.setEveryPageCount(EXPORT_SIZE);
        param.setPage(page);


        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "按照门店查询列表详情");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            List<ScoreGiftCountByScoreDetailResponse> list = getExportScoreGiftCountByStoreDetail(session, param);
            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            bw.append("序号").append(",")
                    .append("兑换时间").append(",")
                    .append("会员卡号").append(",")
                    .append("会员名称").append(",")
                    .append("手机号").append(",")
                    .append("兑换积分").append(",")
                    .append("兑换规则").append(",")
                    .append("当前可用积分").append(",")
                    .append("操作人").append(",")
                    .append("来源").append(",").append("\r");
            if (list != null && !list.isEmpty()) {
                for (int i = 0; i < list.size(); i++) {
                    ScoreGiftCountByScoreDetailResponse data = list.get(i);
                    String createTime = null;
                    if (data.getCreateTime() != null) {
                        createTime = sdf.format(data.getCreateTime());
                    }
                    bw.append(String.valueOf(i + 1)).append(",")
                            .append(createTime == null ? "" : createTime).append(",")
                            .append(data.getMemberCardNum() == null ? "" : data.getMemberCardNum()).append(",")
                            .append(data.getName() == null ? "" : data.getName()).append(",")
                            .append(data.getMobile() == null ? "" : data.getMobile()).append(",")
                            .append(data.getScore() == null ? "" : data.getScore().toString()).append(",")
                            .append(data.getRuleName() == null ? "" : data.getRuleName()).append(",")
                            .append(data.getAvailableScore() == null ? "" : data.getAvailableScore().toString()).append(",")
                            .append(data.getStoreUserName() == null ? "" : data.getStoreUserName()).append(",")
                            .append(data.getTerminalTypeName() == null ? "" : data.getTerminalTypeName()).append(",")
                            .append("\r");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            if (osw != null) {
                osw.close();
                osw = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }
    }

    private List<ScoreGiftCountByScoreDetailResponse> getExportScoreGiftCountByStoreDetail(HttpSession session, @Validated @RequestBody ScoreGiftCountByScoreDetailRequest param) throws IllegalAccessException, InvocationTargetException {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        if (param.getStoreId() != null) {
            param.setMerchantUserId(null);
        }
        BeanUtils.copyProperties(condition, param);
        PageUtils.copyPage(condition, param.getPage());
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setMerchantId(user.getMerchantId());

        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByStoreGiftForMerchant(condition);
        return CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByScoreDetailResponse.class);
    }


    /**
     * 按照规则查询前10个积分兑换--商户权限
     *
     * @return 列表
     * @map dataList
     * @see MemberScoreGiftCountByGiftResponse
     */
    @RequestMapping(value = "/count-by-gift-chart-all")
    @Login
    @Permissions("50045")
    public Response scoreGiftCountTop10ByGiftForMerchant(
                                                         @Validated @RequestBody ScoreGiftCountByGiftRequest param) {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        ScoreGiftRuleCountByGiftCondition condition = new ScoreGiftRuleCountByGiftCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setMerchantId(user.getMerchantId());
        PageUtils.copyPage(condition, param.getPage());
        List<ScoreGiftRuleCountByGiftDTO> list =
                mbrScoreGiftRuleCountQuery.countTop10ByGiftForMerchant(condition);

        List<MemberScoreGiftCountByGiftResponse> response = CJBeanUtils.convertCollection(
                list, MemberScoreGiftCountByGiftResponse.class);
        return ResponseUtils.success("dataList", response);
    }


    /**
     * 按照规则查询前10个积分兑换--门店权限
     *
     * @return 列表
     * @map dataList
     * @see MemberScoreGiftCountByGiftResponse
     */
    @RequestMapping(value = "/count-by-gift-chart-its")
    @Login
    @Permissions("51022")
    public Response scoreGiftCountTop10ByGiftForStore(
                                                      @Validated @RequestBody ScoreGiftCountByGiftRequest param) {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        ScoreGiftRuleCountByGiftCondition condition = new ScoreGiftRuleCountByGiftCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setMerchantId(user.getMerchantId());
        condition.setStoreId(user.getStoreId());
        PageUtils.copyPage(condition, param.getPage());
        List<ScoreGiftRuleCountByGiftDTO> list = mbrScoreGiftRuleCountQuery.countTop10ByGiftForStore(condition);
        List<MemberScoreGiftCountByGiftResponse> response = CJBeanUtils.convertCollection(list, MemberScoreGiftCountByGiftResponse.class);
        return ResponseUtils.success("dataList", response);

    }


    /**
     * 按照规则查询列表--商户权限
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftCountByGiftResponse
     */
    @RequestMapping(value = "/count-by-gift-list-all")
    @Login
    @Permissions("50046")
    public Response scoreGiftCountByGiftListForMerchant(
                                                        @Validated @RequestBody ScoreGiftCountByGiftRequest param) {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        ScoreGiftRuleCountByGiftCondition condition = new ScoreGiftRuleCountByGiftCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setMerchantId(user.getMerchantId());
        PageUtils.copyPage(condition, param.getPage());
        PagingResult<ScoreGiftRuleCountByGiftDTO> list = mbrScoreGiftRuleCountQuery.countByGiftForMerchant(condition);
        List<ScoreGiftCountByGiftResponse> respList = CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByGiftResponse.class);
        return ResponseUtils.successPage(param.getPage(), list, "dataList", respList);
    }

    /**
     * 按照规则查询列表--商户权限 导出
     */
    @RequestMapping(value = "/export/count-by-gift-list-all")
    @Login
    public void exportScoreGiftCountByGiftListForMerchant(
                                                          HttpServletResponse response,
                                                          HttpServletRequest request) throws IOException, ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String pageNo = request.getParameter("pageNO");
        ScoreGiftCountByGiftRequest param = new ScoreGiftCountByGiftRequest();
        if ("" != startTime) {
            param.setStartTime(sdf.parse(startTime));
        }
        if ("" != endTime) {
            param.setEndTime(sdf.parse(endTime));
        }

        Page page = new Page();
        if ("" != pageNo) {
            page.setPageNO(Integer.parseInt(pageNo));
        }
        page.setEveryPageCount(EXPORT_SIZE);
        param.setPage(page);


        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "按照规则查询列表");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            List<ScoreGiftCountByGiftResponse> list = getExportScoreGiftCountByGiftListForMerchant(param);
            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            bw.append("序号").append(",")
                    .append("兑换规则").append(",")
                    .append("兑换量").append(",")
                    .append("\r");
            if (list != null && !list.isEmpty()) {
                for (int i = 0; i < list.size(); i++) {
                    ScoreGiftCountByGiftResponse data = list.get(i);
                    bw.append(String.valueOf(i + 1)).append(",")
                            .append(data.getRuleName() == null ? "" : data.getRuleName()).append(",")
                            .append(data.getNum().toString()).append(",")
                            .append("\r");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            if (osw != null) {
                osw.close();
                osw = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }


    }

    private List<ScoreGiftCountByGiftResponse> getExportScoreGiftCountByGiftListForMerchant(@Validated @RequestBody ScoreGiftCountByGiftRequest param) {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        ScoreGiftRuleCountByGiftCondition condition = new ScoreGiftRuleCountByGiftCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setMerchantId(user.getMerchantId());
        PageUtils.copyPage(condition, param.getPage());
        PagingResult<ScoreGiftRuleCountByGiftDTO> list = mbrScoreGiftRuleCountQuery.countByGiftForMerchant(condition);
        return CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByGiftResponse.class);
    }


    /**
     * 按照规则查询列表--门店权限
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftCountByGiftResponse
     */
    @RequestMapping(value = "/count-by-gift-list-its")
    @Login
    @Permissions("51023")
    public Response scoreGiftCountByGiftListForStore(
                                                     @Validated @RequestBody ScoreGiftCountByGiftRequest param) {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        ScoreGiftRuleCountByGiftCondition condition = new ScoreGiftRuleCountByGiftCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setMerchantId(user.getMerchantId());
        condition.setStoreId(user.getStoreId());
        PageUtils.copyPage(condition, param.getPage());
        PagingResult<ScoreGiftRuleCountByGiftDTO> list = mbrScoreGiftRuleCountQuery.countByGiftForStore(condition);
        List<ScoreGiftCountByGiftResponse> respList = CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByGiftResponse.class);
        return ResponseUtils.successPage(param.getPage(), list, "dataList", respList);
    }


    /**
     * 按照规则查询列表--门店权限 导出
     */
    @RequestMapping(value = "/export/count-by-gift-list-its")
    @Login
    public void exportScoreGiftCountByGiftListForStore(HttpSession session,
                                                       HttpServletResponse response,
                                                       HttpServletRequest request) throws ParseException, IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String pageNo = request.getParameter("pageNO");
        ScoreGiftCountByGiftRequest param = new ScoreGiftCountByGiftRequest();
        if ("" != startTime) {
            param.setStartTime(sdf.parse(startTime));
        }
        if ("" != endTime) {
            param.setEndTime(sdf.parse(endTime));
        }

        Page page = new Page();
        if ("" != pageNo) {
            page.setPageNO(Integer.parseInt(pageNo));
        }
        page.setEveryPageCount(EXPORT_SIZE);
        param.setPage(page);

        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "按照规则查询列表");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            List<ScoreGiftCountByGiftResponse> list = getExportScoreGiftCountByGiftListForStore(param);
            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            bw.append("序号").append(",")
                    .append("兑换规则").append(",")
                    .append("兑换量").append(",")
                    .append("\r");
            if (list != null && !list.isEmpty()) {
                for (int i = 0; i < list.size(); i++) {
                    ScoreGiftCountByGiftResponse data = list.get(i);
                    bw.append(String.valueOf(i + 1)).append(",")
                            .append(data.getRuleName()).append(",")
                            .append(data.getNum().toString()).append(",")
                            .append("\r");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            if (osw != null) {
                osw.close();
                osw = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }


    }

    private List<ScoreGiftCountByGiftResponse> getExportScoreGiftCountByGiftListForStore(@Validated @RequestBody ScoreGiftCountByGiftRequest param) {
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        ScoreGiftRuleCountByGiftCondition condition = new ScoreGiftRuleCountByGiftCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setMerchantId(user.getMerchantId());
        condition.setStoreId(user.getStoreId());
        PageUtils.copyPage(condition, param.getPage());
        PagingResult<ScoreGiftRuleCountByGiftDTO> list = mbrScoreGiftRuleCountQuery.countByGiftForStore(condition);
        return CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByGiftResponse.class);
    }

    /**
     * 按照规则查询详情--商户权限
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftCountByGiftDetailResponse
     */
    @RequestMapping(value = "/count-by-gift-detail-all")
    @Login
    @Permissions("50047")
    public Response scoreGiftCountByGiftDetailForMerchant(
                                                          @Validated @RequestBody ScoreGiftCountByGiftDetailRequest param) throws InvocationTargetException, IllegalAccessException {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setScoreGiftId(param.getScoreGiftId());
        condition.setTerminalType(param.getTerminalType());
        condition.setNameOrMobile(param.getNameOrMobile());
        condition.setStoreName(param.getStoreName());
        condition.setRuleName(param.getRuleName());
        PageUtils.copyPage(condition, param.getPage());

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setMerchantId(user.getMerchantId());
        condition.setStoreId(user.getStoreId());

        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByTimeForMerchant(condition);
        List<ScoreGiftCountByGiftDetailResponse> resList = CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByGiftDetailResponse.class);
        return ResponseUtils.successPage(param.getPage(), list, "dataList", resList);
    }


    /**
     * 按照规则查询详情--商户权限 导出
     */
    @RequestMapping(value = "/export/count-by-gift-detail-all")
    @Login
    public void exportScoreGiftCountByGiftDetailForMerchant(HttpSession session,
                                                            HttpServletResponse response,
                                                            HttpServletRequest request) throws ParseException, IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String terminalType = request.getParameter("terminalType");
        String nameOrMobile = request.getParameter("nameOrMobile");
        String scoreGiftId = request.getParameter("scoreGiftId");
        String pageNo = request.getParameter("pageNO");
        ScoreGiftCountByGiftDetailRequest param = new ScoreGiftCountByGiftDetailRequest();
        if ("" != startTime) {
            param.setStartTime(sdf.parse(startTime));
        }
        if ("" != endTime) {
            param.setEndTime(sdf.parse(endTime));
        }
        if ("" != terminalType) {
            param.setTerminalType(Byte.valueOf(terminalType));
        }
        if ("" != nameOrMobile) {
            param.setNameOrMobile(nameOrMobile);
        }
        if ("" != scoreGiftId) {
            param.setScoreGiftId(Long.parseLong(scoreGiftId));
        }


        Page page = new Page();
        if ("" != pageNo) {
            page.setPageNO(Integer.parseInt(pageNo));
        }
        page.setEveryPageCount(EXPORT_SIZE);
        param.setPage(page);


        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "积分兑换按照规则查询详情");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            List<ScoreGiftCountByGiftDetailResponse> list = getExportScoreGiftCountByGiftDetailForMerchant(session, param);
            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);

            getExportScoreGiftCountByGiftDetailData(sdf, bw, list);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            if (osw != null) {
                osw.close();
                osw = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }

    }

    private List<ScoreGiftCountByGiftDetailResponse> getExportScoreGiftCountByGiftDetailForMerchant(HttpSession session, @Validated @RequestBody ScoreGiftCountByGiftDetailRequest param) {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setScoreGiftId(param.getScoreGiftId());
        condition.setTerminalType(param.getTerminalType());
        condition.setNameOrMobile(param.getNameOrMobile());
        condition.setStoreName(param.getStoreName());
        condition.setRuleName(param.getRuleName());
        PageUtils.copyPage(condition, param.getPage());

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setMerchantId(user.getMerchantId());
        condition.setStoreId(user.getStoreId());

        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByTimeForMerchant(condition);
        return CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByGiftDetailResponse.class);
    }


    /**
     * 按照规则查询详情--门店权限
     *
     * @return 列表
     * @map dataList
     * @see ScoreGiftCountByGiftDetailResponse
     */
    @RequestMapping(value = "/count-by-gift-detail-its")
    @Login
    @Permissions("51024")
    public Response scoreGiftCountByGiftDetailForStore(HttpSession session,
                                                       @Validated @RequestBody ScoreGiftCountByGiftDetailRequest param) throws InvocationTargetException, IllegalAccessException {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setScoreGiftId(param.getScoreGiftId());
        condition.setTerminalType(param.getTerminalType());
        condition.setNameOrMobile(param.getNameOrMobile());
        condition.setStoreName(param.getStoreName());
        condition.setRuleName(param.getRuleName());
        PageUtils.copyPage(condition, param.getPage());

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setMerchantId(user.getMerchantId());
        condition.setStoreId(user.getStoreId());

        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByTimeForStore(condition);
        List<ScoreGiftCountByGiftDetailResponse> resList = CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByGiftDetailResponse.class);
        return ResponseUtils.successPage(param.getPage(), list, "dataList", resList);
    }


    /**
     * 按照规则查询详情--门店权限 导出
     */
    @RequestMapping(value = "/export/count-by-gift-detail-its")
    @Login
    public void exportScoreGiftCountByGiftDetailForStore(HttpSession session,
                                                         HttpServletResponse response,
                                                         HttpServletRequest request) throws ParseException, IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String terminalType = request.getParameter("terminalType");
        String nameOrMobile = request.getParameter("nameOrMobile");
        String scoreGiftId = request.getParameter("scoreGiftId");
        String pageNo = request.getParameter("pageNO");
        ScoreGiftCountByGiftDetailRequest param = new ScoreGiftCountByGiftDetailRequest();
        if ("" != startTime) {
            param.setStartTime(sdf.parse(startTime));
        }
        if ("" != endTime) {
            param.setEndTime(sdf.parse(endTime));
        }
        if ("" != terminalType) {
            param.setTerminalType(Byte.valueOf(terminalType));
        }
        if ("" != nameOrMobile) {
            param.setNameOrMobile(nameOrMobile);
        }
        if ("" != scoreGiftId) {
            param.setScoreGiftId(Long.parseLong(scoreGiftId));
        }


        Page page = new Page();
        if ("" != pageNo) {
            page.setPageNO(Integer.parseInt(pageNo));
        }
        page.setEveryPageCount(EXPORT_SIZE);
        param.setPage(page);


        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "积分兑换按照规则查询详情");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            List<ScoreGiftCountByGiftDetailResponse> list = getExportScoreGiftCountByGiftDetailForStore(session, param);

            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            getExportScoreGiftCountByGiftDetailData(sdf, bw, list);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            if (osw != null) {
                osw.close();
                osw = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }

    }

    private void getExportScoreGiftCountByGiftDetailData(SimpleDateFormat sdf, BufferedWriter bw, List<ScoreGiftCountByGiftDetailResponse> list) throws IOException {
        bw.append("序号").append(",")
                .append("兑换时间").append(",")
                .append("会员卡号").append(",")
                .append("会员名称").append(",")
                .append("手机号").append(",")
                .append("兑换积分").append(",")
                .append("兑换规则").append(",")
                .append("当前可用积分").append(",")
                .append("操作人").append(",")
                .append("来源").append(",").append("\r");

        if (list != null && !list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                ScoreGiftCountByGiftDetailResponse data = list.get(i);
                String createTime = null;
                if (data.getCreateTime() != null) {
                    createTime = sdf.format(data.getCreateTime());
                }
                bw.append(String.valueOf(i + 1)).append(",")
                        .append(createTime == null ? "" : createTime).append(",")
                        .append(data.getMemberCardNum() == null ? "" : data.getMemberCardNum()).append(",")
                        .append(data.getName() == null ? "" : data.getName()).append(",")
                        .append(data.getMobile() == null ? "" : data.getMobile()).append(",")
                        .append(data.getScore() == null ? "" : data.getScore().toString()).append(",")
                        .append(data.getRuleName() == null ? "" : data.getRuleName()).append(",")
                        .append(data.getAvailableScore() == null ? "" : data.getAvailableScore().toString()).append(",")
                        .append(data.getStoreUserName() == null ? "" : data.getStoreUserName()).append(",")
                        .append(data.getTerminalTypeName() == null ? "" : data.getTerminalTypeName()).append(",")
                        .append("\r");
            }
        }
    }

    private List<ScoreGiftCountByGiftDetailResponse> getExportScoreGiftCountByGiftDetailForStore(HttpSession session, @Validated @RequestBody ScoreGiftCountByGiftDetailRequest param) {
        MemberScoreGiftByTimeCondition condition = new MemberScoreGiftByTimeCondition();
        condition.setStartTime(param.getStartTime());
        condition.setEndTime(param.getEndTime());
        condition.setScoreGiftId(param.getScoreGiftId());
        condition.setTerminalType(param.getTerminalType());
        condition.setNameOrMobile(param.getNameOrMobile());
        condition.setStoreName(param.getStoreName());
        condition.setRuleName(param.getRuleName());
        PageUtils.copyPage(condition, param.getPage());

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        condition.setMerchantId(user.getMerchantId());
        condition.setStoreId(user.getStoreId());

        PagingResult<MemberScoreGiftListDTO> list = mbrScoreGiftRuleCountQuery.queryByTimeForStore(condition);
        return CJBeanUtils.convertCollection(list.getItems(), ScoreGiftCountByGiftDetailResponse.class);
    }


}
